package com.fromcloudtocloud.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.util.CharsetUtil;

import java.util.List;

/**
 * @author stevejson
 */
public class MessageCodec extends MessageToMessageCodec {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, List out) throws Exception {
        System.out.println("消息正在编码");
        String string = (String) msg;
        out.add(Unpooled.copiedBuffer(string, CharsetUtil.UTF_8));
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, Object msg, List out) throws Exception {
        System.out.println("正在消息解码");
        ByteBuf byteBuf = (ByteBuf) msg;
        String string = byteBuf.toString(CharsetUtil.UTF_8);
        // 传递到下一个handler
        out.add(string);
    }
}
